package com.leap.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leap.entity.AccountCategoryView;
import com.leap.entity.History;
import com.leap.mapper.HistoryMapper;
import com.leap.service.HistoryService;
import com.leap.utils.Const;
import com.leap.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
public class HistoryServiceImpl extends ServiceImpl<HistoryMapper, History> implements HistoryService {

    @Autowired
    private JwtUtils utils;

    @Override
    public List<Long> getArticleIdListByToken(String headerToken) {

        Long accountIdByToken = utils.getAccountIdByToken(headerToken);

        LambdaQueryWrapper<History> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(History::getAccountId, accountIdByToken);
        queryWrapper.orderByDesc(History::getUpdateTime);

        List<History> historyList = this.list(queryWrapper);

        return historyList.stream().map(History::getArticleId).toList();
    }

    @Override
    public void insertHistory(Long articleId, String headerToken) {
        Long accountId = utils.getAccountIdByToken(headerToken);
        LambdaUpdateWrapper<History> updateWrapper = new LambdaUpdateWrapper<>();

        updateWrapper.eq(History::getAccountId, accountId)
                .eq(History::getArticleId, articleId)
                .set(History::getUpdateTime, LocalDateTime.now());

        if(!update(updateWrapper)){
            History history = History.builder()
                    .articleId(articleId)
                    .accountId(accountId)
                    .build();
            save(history);
        }

    }
}
